package com.ztjava.core.interceptor;

import java.util.List;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.upload.UploadFile;
import com.ztjava.core.Constant;
import com.ztjava.ext.auth.bean.AuthSession;
import com.ztjava.ext.auth.tool.AuthTool;

public class FilesInterceptor implements Interceptor{
	//因为getFiles前获取不了参数，影响api获取认证信息，所以单独写个
	@Override
	public void intercept(Invocation inv){
		Controller c = inv.getController();
		List<UploadFile> fileList = null;
		try{
			fileList = c.getFiles();
		}catch (Exception e) {
			e.printStackTrace();
			inv.getController().setAttr(Constant.RESULT, Constant.ERROR);
			inv.getController().setAttr(Constant.MESSAGE,"没有找到上传文件，请确保Content-Type: multipart/form-data");
			inv.getController().renderJson(new String[]{Constant.RESULT,Constant.MESSAGE});
			return;
		}
		String sessionId = inv.getController().getPara(AuthTool.token_name);
		if(sessionId==null||sessionId.equals("")){
			inv.getController().setAttr(Constant.RESULT, Constant.TIMEOUT);
			inv.getController().setAttr(Constant.MESSAGE,"请先登录");
			inv.getController().renderJson(new String[]{Constant.RESULT,Constant.MESSAGE});
			return;
		}
		// 使用Redis共享缓存
		Cache cache = Redis.use();
		AuthSession authSession = cache.get(sessionId);
		if(authSession==null){
			inv.getController().setAttr(Constant.RESULT, Constant.TIMEOUT);
			inv.getController().setAttr(Constant.MESSAGE,"请先登录");
			inv.getController().renderJson(new String[]{Constant.RESULT,Constant.MESSAGE});
			return;
		}
		inv.getController().setAttr(Constant.AUTHSESSION, authSession);

		if(fileList==null||fileList.size()==0){
			inv.getController().setAttr(Constant.RESULT, Constant.ERROR);
			inv.getController().setAttr(Constant.MESSAGE,"没有找到上传文件！");
			inv.getController().renderJson(new String[]{Constant.RESULT,Constant.MESSAGE});
			return;
		}
		c.setAttr("fileList", fileList);
		inv.invoke();
	}

}
